<template>
  <el-input v-model="input" v-bind="$attrs" disabled>
    <template #append>
      <el-popover placement="bottom" :width="400" trigger="click">
        <template #reference>
          <el-button>
            <el-icon><Search /></el-icon>
          </el-button>
        </template>
        <template #default>
          <section class="icon-search">
            <el-input
              v-model="searchInput"
              placeholder="请输入关键词进行筛选"
            />
          </section>
          <div class="icon-list">
            <section
              class="icon-item"
              v-for="icon in iconOptions"
              :key="icon"
              @click="handleClick(icon)"
            >
              <el-icon class="icon-each"
                ><component :is="icon" class="icon-each"
              /></el-icon>
              <span :title="icon">{{ icon }}</span>
            </section>
          </div>
        </template>
      </el-popover>
    </template>
  </el-input>
</template>

<script>
import { ICONS } from "@constants/icons"

export default {
  inheritAttrs: false,
  props: ["modelValue"],
  emits: ["update:modelValue"],
  data() {
    return {
      iconOptions: [],
      searchInput: ""
    }
  },
  computed: {
    input: {
      get() {
        return this.modelValue
      },
      set(value) {
        this.$emit("update:modelValue", value)
      }
    }
  },
  methods: {
    handleClick(icon) {
      this.input = icon
      this.searchInput = ""
    }
  },
  watch: {
    searchInput(n) {
      clearTimeout(() => this.searchInputTimeout)
      this.searchInputTimeout = setTimeout(() => {
        this.iconOptions = n
          ? this._iconOptions.filter(name => new RegExp(n, "i").test(name))
          : [...this._iconOptions]
      }, 700)
    }
  },
  created() {
    this._iconOptions = this.iconOptions = ICONS
  }
}
</script>

<style lang="scss" scoped>
.icon-search {
  margin-bottom: 4px;
}
.icon-list {
  width: 385px;
  display: grid;
  grid-template-columns: repeat(3, 120px);
  gap: 4px 4px;
  height: 200px;
  overflow-y: auto;

  .icon-item {
    display: flex;
    align-items: center;
    gap: 4px;
    height: 1.2rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    cursor: pointer;
    &:hover {
      color: var(--el-color-primary);
    }

    .icon-each {
      width: 1.2rem;
      height: 1.2rem;
    }
  }
}
</style>
